package pro.seac.twitter.application.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import pro.seac.twitter.application.dto.UserViewEntry;
import pro.seac.twitter.domain.UserAccount;

@Component
public class UserAccountDao extends BaseDao<UserAccount, Integer> {

	@Autowired
	public UserAccountDao(SessionFactory sessionFactory) {
		super(sessionFactory, UserAccount.class);
	}

	public UserAccount findByUserName(String username) {
		return (UserAccount) getSession().createQuery("FROM UserAccount u WHERE u.username=:username").setString("username", username).uniqueResult();
	}

	// TODO To nie jest najlepszy sposob na wyciaganie DTO dla widoku, na razie jednak mysle ze wystarczy
	@SuppressWarnings("unchecked")
	public List<UserViewEntry> getAll() {
		String className = UserViewEntry.class.getCanonicalName();
		String hql = "SELECT new " + className + "(u.id, u.createdDate, u.username, u.email, u.name, u.about) FROM UserAccount u";
		return getSession().createQuery(hql).//
				list();
	}

	public UserViewEntry getByUserName(String username) {
		String className = UserViewEntry.class.getCanonicalName();
		String hql = "SELECT new " + className + "(u.id, u.createdDate, u.username, u.email, u.name, u.about) FROM UserAccount u WHERE u.username=:username";
		return (UserViewEntry) getSession().createQuery(hql).//
				setString("username", username).//
				uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<UserViewEntry> getFollowersById(Integer id) {
		String className = UserViewEntry.class.getCanonicalName();
		String hql = "SELECT new " + className + "(f.id, f.createdDate, f.username, f.email, f.name, f.about) FROM UserAccount u join u.followers f WHERE u.id=:id";
		return getSession().createQuery(hql).//
				setInteger("id", id).//
				list();
	}

	@SuppressWarnings("unchecked")
	public List<UserViewEntry> getFollowedById(Integer id) {
		String className = UserViewEntry.class.getCanonicalName();
		String hql = "SELECT new " + className + "(f.id, f.createdDate, f.username, f.email, f.name, f.about) FROM UserAccount u join u.followed f WHERE u.id=:id";
		return getSession().createQuery(hql).//
				setInteger("id", id).//
				list();
	}

	@SuppressWarnings("unchecked")
	public List<Integer> getFollowedIdsById(Integer id) {
		String hql = "SELECT f.id FROM UserAccount u join u.followed f WHERE u.id=:id";
		return getSession().createQuery(hql).//
				setInteger("id", id).//
				list();
	}
}
